package com.gin.kotlin.gf2gamecommunity.base.util

import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.TextFieldValue
import java.util.regex.Pattern

/**
 * 向当前选中位置的前或后插入文本
 * @receiver TextFieldValue
 * @param textStart 在选中位置前插入的文本
 * @param textEnd 在选中位置后插入的文本
 */
fun TextFieldValue.insertBySelection(textStart: String = "", textEnd: String = ""): TextFieldValue {
    val newText = StringBuilder(this.text)
        .insert(selection.end, textEnd)
        .insert(selection.start, textStart)
        .toString()
    val length = textStart.length
    val newRange = TextRange(selection.start + length, selection.end + length)
    return this.copy(text = newText, selection = newRange)
}

private val TWITTER_IMG_PATTERN = Pattern.compile("\\D*(\\d{19})\\D*")
private val PIXIV_IMG_PATTERN = Pattern.compile("(\\d+)_p\\d+")

/**
 * 尝试根据文件名返回图片来源
 * @param filename String
 * @return String?
 */
fun findSource(filename: String): String? {
    val pixivUrl = PIXIV_IMG_PATTERN.matcher(filename).takeIf { it.find() }?.group(1)?.let { "https://www.pixiv.net/artworks/$it" }
    val twitterUrl = TWITTER_IMG_PATTERN.matcher(filename).takeIf { it.find() }?.group(1)?.let { "https://x.com/i/status/$it" }
    return twitterUrl ?: pixivUrl
}

fun htmlLink(url: String, text: String? = null) = "<a href='${url}' target='_blank'>${text ?: url}</a>"